import React, {Component} from 'react'
import {Table as AntTable, Menu, Dropdown, Icon, Button, Select, Anchor} from 'antd'
import {Link as Linko} from 'react-router-dom'
import moment from 'moment';
import QRCode from 'qrcode.react'
import {connect} from 'react-redux'
import {detail} from './../../actions/info'
import './../../common/table.css'

const {Link} = Anchor;
const styles = ['neutral', 'positive', 'reverse']
const Option = Select.Option;

//已阅未阅
class Readtag extends Component {
  constructor(props) {
    super(props);
    if (!localStorage.readTopic) {
      localStorage.readTopic = JSON.stringify(["0"])
    }
    let Hlist = JSON.parse(localStorage.readTopic)
    let isHas = Hlist.indexOf(this.props.tagId) >= 0
    this.state = {
      collection: isHas,
    }
  }
  handleClick(value) {
    if (!this.state.collection) {
      let list = JSON.parse(localStorage.readTopic)
      list.push(this.props.tagId)
      localStorage.readTopic = JSON.stringify(list)
    }
    this.setState(prevState => ({
      collection: !prevState.collection
    }))
  }

  render() {
    if (!localStorage.readTopic) {
      localStorage.readTopic = JSON.stringify(["0"])
    }
    let Hlist = JSON.parse(localStorage.readTopic)
    let isHas = Hlist.indexOf(this.props.tagId) >= 0
    return (
      <span className={isHas ? "opti hasread" : 'opti noread'}
            onClick={() => this.handleClick(isHas ? this.props.title[0] : this.props.title[1])}>
          <Icon
            type={isHas ? this.props.icon[0] : this.props.icon[1]}/>{isHas ? this.props.title[0] : this.props.title[1]}</span>
    )
  }
}

class Etag extends Component {
  constructor(props) {
    super(props);
    this.state = {
      publish: this.props.publish
    }
  }

  handleClick(id, tit, content) {
    this.setState(prevState => ({
      publish: !prevState.publish
    }))
    this.props.onCtrClick("上报",id,tit,content)
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      publish: nextProps.publish
    })
  }

  render() {
    if (!this.state.publish) {
      return <span className="opti" onClick={() => this.handleClick(this.props.id, this.props.tit, this.props.content)}><Icon
        type="upload"></Icon>{this.state.publish ? '已上报' : '上报'}</span>
    } else {
      return <span className="opti"><Icon type="upload"></Icon>{this.state.publish ? '已上报' : '上报'}</span>
    }

  }
}

class Tagmark extends Component {
  constructor(props) {
    super(props);
    this.state = {}
  }

  handleClick(e) {
    this.props.chageId(this.props.ID)
  }

  render() {
    return (
      <label className="check-label">
        <input type="radio" name="mark" onChange={(e) => this.handleClick(e)}/>
        <span className="opti">
          <Icon type="tags"/>书签</span>
      </label>
    )
  }
}

class Tag extends Component {
  constructor(props) {
    super(props);
    this.state = {
      collection: this.props.collection
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      collection: nextProps.collection
    })
  }

  handleClick(value) {
    this.setState(prevState => ({
      collection: !prevState.collection
    }));
    this.props.onCtrClick(this.state.collection ? this.props.title[0] : this.props.title[1],
      this.props.id,this.props.tit,this.props.content,this.props.poTime,this.props.webSite,this.props.domain,this.props.positiveOrNegative);
  }

  render() {
    return (
      <span className="opti"
            onClick={() => this.handleClick(this.state.collection ? this.props.title[0] : this.props.title[1])}><Icon
        type={this.state.collection ? this.props.icon[0] : this.props.icon[1]}/>{this.state.collection ? this.props.title[0] : this.props.title[1]}</span>
    )
  }
}

const Btn = (props) => ({
  render() {
    return (
      <span className="opti" onClick={() => {
        this.props.onCtrClick(this.props.title,this.props.id)
      }}><Icon type={this.props.icon}></Icon>{this.props.title}</span>
    )
  }
})

class OverlayVisible extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      value: ''
    };
  }

  handleMenuClick = (e) => {
    this.setState({
      value: this.props.oValue
    })

  }
  handleVisibleChange = (flag) => {
    this.setState({visible: flag});
  }

  fn_render = (flag, b) => {
    if (flag) {
      return <QRCode value={b}/>
    }
    else {
      return
    }
  }

  handhover() {
    this.setState({visible: false});
  }

  render() {
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        <Menu.Item key="1">微信</Menu.Item>
        <Menu.Item key="2">微博</Menu.Item>
      </Menu>
    )

    return (
      <div className="share-pos">
        <Dropdown overlay={menu} onVisibleChange={this.handleVisibleChange} visible={this.state.visible}>
          <span className="ant-dropdown-link"><Icon type="share"/>分享</span>
        </Dropdown>
        <div className={this.state.visible ? 'post show' : 'post hide'} onMouseOver={() => this.handhover()}>
          {this.fn_render(true, this.state.value)}
        </div>
      </div>
    )
  }

}

@connect(
  state => state.inforesult,
  {detail}
)

export default class Table extends Component {
  constructor(props) {
    super(props);
    this.mountProps(props);
    this.state = {
      id: '#'
    }
    this.handleChange = this.handleChange.bind(this)
  }

  componentWillReceiveProps(props) {
    this.mountProps(props);
  }

  fnPensity(value) {
    var typrht = ''
    switch (value) {
      case -1:
        return typrht = '全部'
      case 0:
        return typrht = '中性'
      case 1:
        return typrht = '正面'
      case 2:
        return typrht = '负面'
      default:
        return typrht = value
    }
    return typrht
  }

  changeId(Id) {
    this.setState({
      id: '#' + Id
    })
  }

  //链接跳转id设置
  detailset(id, key) {
    if (!localStorage.id) {
      localStorage.id = id;
      localStorage.titleContentPrint = key;
    } else {
      localStorage.id = id;
      localStorage.titleContentPrint = key
    }
  }

  createMarkup(page) {
    // console.log(page)
    // this.keyLight(page,'再谈')
    let res = page.replace(/<br \/>/g, '').replace(/<br\/>/g, '').replace(/{{{/g, "<span class='light' style='color:red'>").replace(/}}}/g, "</span>")
    return {__html: res};
  };

  mountProps(props) {
    const {
      header,
      action,
      headerWidth,
      // currentPage,
      data,
    } = props;
    /*this.state = {
      currentPage,

    }*/
    this.makeColumns(header, action, headerWidth, data);
  }

  makeColumns(headers, action, headerWidth, data) {
    this.columns = [{
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <div className="srcpos">
          {/* <img className="src1" src={record.domain===' '?'image/defult':'image/'+record.domain +'.png'}  alt=""></img> */}
          <img className="src1" src={'image/' + record.domain + '.png'} alt=""></img>
          <img className="src2" src={'image/defult.png'} alt=""></img>
        </div>
      ),
    }, {
      dataIndex: 'address',
      key: 'address',
      render: (text, record) => (
        <div className="fiter-info" id={record.id}>
          <div className="title-p">
            <Linko to={'/detail?t=' + Date.parse(new Date()) + '&type=' + (record.favoriteId ? 1 : 0)} target='_blank'>
              <div className='titl' onClick={() => this.detailset(record.id, record.titleContentPrint)}
                   dangerouslySetInnerHTML={this.createMarkup(record.title.replace(/<br\/>/g, '').replace(/{{{/g, "<span class='light' style='color:red'>").replace(/}}}/g, "</span>"))}></div>
            </Linko>
            <div className={"type " + styles[record.positiveOrNegative]}>{this.fnPensity(record.positiveOrNegative)}</div>
            <div style={{position:'absolute',right:0,fontSize:12,color:'#9ba2ab'}}>{moment(new Date().setTime(record.poTime)).format('YYYY-MM-DD HH:mm:ss')}</div>
          </div>

          <div className="info show"
               dangerouslySetInnerHTML={this.createMarkup(record.content)}></div>
          <div className="footer">
            <div className="source">
              <span>来源：</span>
              <span>{record.webSite}</span>
            </div>

            <div className="share">
              <OverlayVisible oValue={record.url}></OverlayVisible>
              <Etag id={record.id} onCtrClick={this.props.click} publish={record.publish} tit={record.title}
                    content={record.content}></Etag>
              <Tag icon={['star', 'star-o']} title={['已收藏', '收藏']} onCtrClick={this.props.click} id={record.id}
                   tit={record.title} content={record.content} poTime={record.poTime}
                   webSite={record.webSite} domain={record.domain} positiveOrNegative={record.positiveOrNegative}
                   collection={record.collected}></Tag>
              <Readtag icon={['eye-o', 'eye']} title={['取消已阅', '标记已阅']} tagId={record.id}></Readtag>
              <Tagmark ID={record.id} chageId={(value) => this.changeId(value)}></Tagmark>
              <Btn icon={'delete'} onCtrClick={this.props.click} title='删除' id={record.id}></Btn>
            </div>
          </div>
        </div>
      )
    }];
  }
  // 当前页点击变化
  onPageChangeHandler = (currentPage) => {
    this.props.onChange(currentPage)
  };
  // 每页显示条数限制
  handleChange(value) {
    this.props.changeSize(Number(value))
    // console.log(`selected ${value}`);
  };
  // 批量删除按钮
  deleteChange = () => {
    this.props.deleteMultiple();
  };
  // 批量标记为已阅
  haveRead = () => {
    this.props.readingList();
  };
  // 导出
  exportBtn = () => {
    this.props.exportInfo();
  };
  render() {
    return (
      <div>
        <div className="t">
          <Button onClick={this.deleteChange}>删除</Button>
          <Button onClick={this.exportBtn}>导出</Button>
          <Button onClick={this.haveRead}>标记为已阅</Button>
          <Anchor>
            <Link href={this.state.id} title="返回书签" showInkInFixed={false} affix={false}></Link>
          </Anchor>
            <Button>批量上报</Button>
          <Select style={{width: 200}} onChange={this.handleChange} defaultValue={'10条/页'}>
            <Option value="10">10条/页</Option>
            <Option value="5">5条/页</Option>
            <Option value="50">50条/页</Option>
          </Select>
        </div>
        <AntTable
          rowKey="id"
          rowSelection={this.props.rowSelection}
          columns={this.columns}
          dataSource={this.props.data}
          deleteMultiple={this.deleteChange}
          readingList={this.haveRead}
          exportInfo={this.exportBtn}
          pagination={this.props.pagination !== false ? {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.currentIndeX,
            onChange: this.onPageChangeHandler,
            showTotal(total, range) {
              return <span className={'pageTotal'}>共<span className={'count'}>{total}</span>条</span>;
            },
          } : false}></AntTable>
      </div>
    )
  }
}